//
//  KABillListVC.swift
//  kano
//
//  Created by Frank on 2024/9/12.
//

import Foundation
import UIKit
import Flutter

class KABillListVC: KABaseVC {
    static let var_itemCellId = "KABillListCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView(frame: CGRect(x: 0.0, y: UIDevice.ka_fullNavHeight, width: view.width, height: UIDevice.ka_viewHeight), style: .grouped)
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        var_tableView.register(KABillListCell.self, forCellReuseIdentifier: Self.var_itemCellId)
        var_tableView.register(KABillListSectionHeader.self, forHeaderFooterViewReuseIdentifier: "KABillListSectionHeader")
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.separatorColor = UIColor.clear
        var_tableView.backgroundColor = .white
        var_tableView.tableHeaderView = tableHeader
        return var_tableView
    }()
    
    lazy var tableHeader: KABillListHeader = {
        tableHeader = KABillListHeader(frame: CGRectMake(0, 0, var_screenWidth, kscale(252)))
        tableHeader.var_billListTip.handler = {
            self.requestAlertInfo()
        }
        return tableHeader
    }()
    
    lazy var emptyView: KAEmptyView = {
        emptyView = KAEmptyView(frame: CGRectMake(0, 350, var_screenWidth, 100))
        emptyView.handler = {
            //self.applyAuto()
            self.ka_limitButtonClick()
        }
        return emptyView
    }()
    
    var auditState: KAAuditState?
    var homeInfo: KAHomeInfo?
    var productInfo: KAProductInfo?
    
    //"softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions, "loanTransactionIdentifier": model?.loanList?.first?.loanGid,
    func requestAlertInfo() {
        let paraDic: [String : Any] = ["newPassphrase": 1,]
        billProvider.request(.penalty(paraDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KABillListModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            let subStr = "If you fail to repay by 24:00 of due date, we shall levy a late payment fee at 3% on principal for account management, and a delayed interest at 1.7% flat per day(2.5% flat for 10-20 days overdue, and 3% flat per day for more than 20 days overdue) . Please repay on time."
                            let alert = KAAlertView.alert(withTitle: "Description of penalty fee", subtitle: subStr) { clickedTitle in
                            }
                            alert.addAction(KAAlertAction(title: "OK", titleColor: .blue, backgroundColor: .clear))
                            alert.show()
                        }
                    }
                }else {
                    view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    
    var model: KABillListModel?
    var overdueLoans: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view.addSubview(var_tableView)
        
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Bill"
        
        requestData()
        
        let data = KAPageInfo(eleId: "BillStatement_Overview", path: "\(KABillListVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
    }
    
    func requestData() {
        view.showLoading()
        let paraDic = [ "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions ]
        billProvider.request(.billList(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KABillListModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            model = content
                            if model?.accessTemporaryToken?.count ?? 0 > 0 {
                                tableHeader.model = model!
                                var_tableView.reloadData()
                            } else {
                                var_tableView.addSubview(emptyView)
                                ka_requestHomeInfo()
                            }
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    
}

extension KABillListVC : UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return model?.accessTemporaryToken?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let loan = model?.accessTemporaryToken?[indexPath.row] else {return UITableViewCell()}
        let var_cell: KABillListCell = KABillListCell.ka_cell(for: tableView)
        var_cell.repayHandler = {
            //            self.navigationController?.pushViewController(KARepaymentDetails(with: loan.loanTransactionIdentifier), animated: true)
            KAFlutterManager.showFlutterVC(route: "/repayment?loanTransactionIdentifier=\(loan.loanTransactionIdentifier)", parameter: [:])
        }
        var_cell.model = loan
        var_cell.headerBg.isHidden = (indexPath.row == 0 && tableHeader.overdueLoans > 0) ? false : true
        return var_cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let loan = model?.accessTemporaryToken?[indexPath.row] else { return 0.00 }
        if loan.tadpoleLoanIndicator || loan.operationalStatus == 8 ||  loan.operationalStatus == 99 {
            return kscale(213)
        }
        return kscale(152)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let loan = model?.accessTemporaryToken?[indexPath.row] else {return}
        let vc = KABillDetailVC(with: loan.loanTransactionIdentifier)
        navigationController?.pushViewController(vc, animated: true)
        
        let btnInfo = KABtnInfo(eleId: "BillToDetail_Nav", pageId: "BillStatement_Overview", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableHeader.overdueLoans > 0 {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KABillListSectionHeader") as! KABillListSectionHeader
            header.handler = {
                KAFlutterManager.showFlutterVC(route: "/onlineService", parameter: ["mobile" : KAUserManager.shared.user.notificationMessage])
            }
            return header
        }
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableHeader.overdueLoans > 0 {
            return kscale(50)
        }
        return 0.00
    }
    
}


extension KABillListVC {
    
    @objc func ka_limitButtonClick() {
        //        let hasOverdue = homeInfo?.voucherConfigurationId?.sorted {$0. > $1}
        //是否已授信 && 授信额度!=0
        if auditState?.auditCondition == 1 && productInfo?.loanInterestPercentage != 0  {
            //可借额度 小于 最小借款金额，提示额度不足
            if productInfo!.borrowingCapacity < (productInfo!.refusalIndicator?.first?.relatedTypeIdentifier)! {
                let subTitle = "Your borrowing limit is insufficient and you need to reach ₦Naira to borrow normally"
                let replacedString = subTitle.replacingOccurrences(of: "Naira", with: "\(productInfo?.refusalIndicator?.first?.relatedTypeIdentifier ?? 0)")
                let alert = KAAlertView.alert(withTitle: "", subtitle: replacedString) { _ in
                }
                alert.addAction(KAAlertAction(title: "Confirm", titleColor: .blue, backgroundColor: .clear) { action in
                    
                })
                alert.show()
            }
            //是否有逾期账单，有提示去还款
            else if homeInfo?.voucherConfigurationId?.contains(where: { $0.overdueDuration > 0 }) == true {
                view.makeToast("You have overdue loan, please apply loan after repay")
            }
            //去借款
            else {
                applyAuto()
            }
        } else {
            applyAuto()
        }
    }
    
    func applyAuto() {
        if homeInfo != nil {
            NetService.applyAuto(borrowingLoanType: homeInfo!.loanTypeForBorrowing) { isSuccess, message, response in
                
            }
        }
    }
    
    func ka_requestHomeInfo() {
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        NetService.ka_requestHomeInfo { [self] isSuccess, message, response in
            if isSuccess {
                guard let content = response?.voucherQuantity else { return }
                homeInfo = content
                if (content.marketPromotion == 1) {
                    //用户首次授信成功
                    KAAFTool.logEvent(event: "SKP_Firstsuccessfulcredit_extension")
                }
                if (content.actionButtonStyle == 1) {
                    //首次获取额度成功
                    KAAFTool.logEvent(event: "SKP_Successfullyobtained_creditfirst")
                }
                productInfo = NetService.getActiveProduct(content: content)
            } else {
                self.view.makeToast(badNetWorking)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        NetService.ka_requestHomeStatus { [self] isSuccess, message, response in
            if isSuccess {
                guard let content = response?.voucherQuantity else { return }
                auditState = content
            } else {
                self.view.makeToast(badNetWorking)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.notify(queue: .main) {
            
        }
    }
}
